const Service = require('egg').Service

class MenuService extends Service {
	constructor(ctx) {
		super(ctx)
	}
	async index(username) {
		const { id } = await this.ctx.model.User.findOne({
			where: { username },
		})
		const { role } = await this.ctx.model.UserInfo.findOne({
			where: { userId: id },
		})
		let menus = await this.ctx.model.Menu.findAll({
			raw: true,
		})
		menus = menus.filter(menu => JSON.parse(menu.roleLevel).includes(role))
		const data = this.ctx.helper.toTree(menus)
		return {
			status: 'success',
			data,
		}
	}
	async create(body) {
		try {
			await this.ctx.model.Menu.create({
				...body,
			})
			return 'success'
		} catch (e) {
			return JSON.stringify(e)
		}
	}

	async update(id, body) {
		try {
			await this.ctx.model.Menu.update(
				{ ...body },
				{
					where: { id },
				}
			)
			return 'success'
		} catch (e) {
			return JSON.stringify(e)
		}
	}
	async show(id) {
		try {
			const data = await this.ctx.model.Menu.findOne({
				where: { id },
			})
			return {
				status: 'success',
				data,
			}
		} catch (e) {
			return JSON.stringify(e)
		}
	}
}
module.exports = MenuService
